import { ref, reactive, onMounted, } from "vue";
import { useRoute } from "vue-router";
import qs from "qs";
import { ElMessage } from "element-plus";
import {
  GetFilterSecurityCreditRating,
  GetCreditEnhancement,
  GetAllByAssetTransferId,
  GetInfoByAssetTransferId,
  SecuritiesDeclarationProfilesCreate,
  GetAllDeclarationProfiles,
  GetSPVName,
  SecurityCreditRatingGetInfo,
  PredeterminedRating,
  GetSecurityCreditRatingPageSet,
  GetStockExchangeName
} from "@/api/stu/SupplyChainFinance";
import { nextTick } from "process";
export function usePortrait() {
  const route = useRoute()
  const filterDataList = ref([])
  const showReport = ref<boolean>(false);
  const informationDialog = ref<boolean>(false);
  const isShowSave = ref<boolean>(false);
  const selectItem = ref()
  const filterSelectId = ref('')
  const selectName = ref()
  const selectAssetPoolId = ref()
  const selectSecurityCreditRatingId = ref()
  const projectpProposalsData = ref() //出具项目方案数据
  const reportData = ref()
  const allListVisible = ref(false)
  const allNeedDay = reactive({
    gradeStrong: '',
    spvName: '', resultStr: '',
    stockExchangeName: ''
  })
  const dataList = ref([])
  const columns1: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "项目名称",
      prop: "assetSecuritizationName",
    },
    {
      label: "状态",
      prop: "isUploadFile",
      minWidth: 200,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isUploadFile ? "success" : "warning"}>
          <span>
            {row.isUploadFile ? "已完成" : "未完成"}
          </span>
        </el-tag>

      )
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "资料类型",
      prop: "name",
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const declareList = ref([
    {
      name: '资料准备',
      status: '0',
    },
    {
      name: '项目初步评估',
      status: '0',
    },
    {
      name: '出具项目方案',
      status: '0',
    },
    {
      name: '尽职调查',
      status: '0',
    },
    {
      name: '挂牌转让申请书',
      status: '0',
    },
    {
      name: '计划说明书',
      status: '0',
    },
    {
      name: '法律意见书',
      status: '0',
    },
    {
      name: '信用评级报告',
      status: '0',
    }, {
      name: '主要交易合同文本',
      status: '0',
    },
    {
      name: '其他中介报告',
      status: '0',
    },
    {
      name: '其他资料',
      status: '0',
    },
  ])
  onMounted(async () => {
    getList()
  })

  async function getList() {
    const data = qs.stringify({
      taskId: route.query.taskId,
      planId: route.query.planId
    })
    let res1 = await GetSecurityCreditRatingPageSet(data)
    if (res1.success) {
      dataList.value = res1.data
    } else {
      ElMessage.error(res1.msg)
    }
  }
  //切换项目获取增级列表 + 制定方案列表
  function filterProject(a) {
    filterSelectId.value = a.assetTransferId
    selectName.value = a.assetSecuritizationName
    selectAssetPoolId.value = a.assetPoolId
    selectSecurityCreditRatingId.value = a.securityCreditRatingId
    allListVisible.value = true
    handleChangeStatus()
  }

  async function showInformation(item) {
    isShowSave.value = false
    if (item.status == 1) {
      isShowSave.value = true
    } else {
      isShowSave.value = false
    }
    selectItem.value = item
    //处理需要获取数据的报告
    if (item.name == '出具项目方案') {
      const data1 = qs.stringify({
        assetTransferId: filterSelectId.value
      })
      let res1 = await GetInfoByAssetTransferId(data1)
      if (res1.success) {
        projectpProposalsData.value = res1.data
      } else {
        ElMessage.error(res1.msg)
      }
      const data = qs.stringify({
        assetTransferId: filterSelectId.value,
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      let res = await GetCreditEnhancement(data)
      if (res.success) {
        allNeedDay.gradeStrong = res.data.map(item =>
          item.creditEnhancementName
        ).join(',')
      } else {
        ElMessage.error(res.msg)
      }
    }
    if (item.name == '挂牌转让申请书') {
      const data1 = qs.stringify({
        assetTransferId: filterSelectId.value
      })
      let res4 = await GetSPVName(data1)
      if (res4.success) {
        allNeedDay.spvName = res4.data.spvCompanyName
      } else {
        ElMessage.warning(res4.msg)
      }

      const data2 = qs.stringify({
        id: selectAssetPoolId.value
      })
      let res5 = await GetStockExchangeName(data2)
      if (res5.success) {
        allNeedDay.stockExchangeName = res5.data
      } else {
        ElMessage.warning(res5.msg)
      }
    }
    if (item.name == '信用评级报告') {
      const data1 = qs.stringify({
        securityCreditRatingId: selectSecurityCreditRatingId.value
      })
      let res4 = await SecurityCreditRatingGetInfo(data1)
      if (res4.success) {
        res4.data.creditEnhancementRanking = JSON.parse(res4.data.creditEnhancementRanking)
        const item = res4.data
        let res = await PredeterminedRating(data1)
        const gradeArr = ['A', 'AA', 'AAA', 'B', 'BB', 'BBB', 'C', 'CC', 'CCC']
        for (var i = 0; i < item.creditEnhancementRanking.length; i++) {
          const index = gradeArr.findIndex(a => a == res.data)// 根据索引获取对应的等级
          const resultIndex = index + i
          item.creditEnhancementRanking[i].preGrade = gradeArr[resultIndex]
          console.log(item.creditEnhancementRanking[i]);
        }
        var result = "";
        for (var i = 0; i < item.creditEnhancementRanking.length; i++) {
          result += `${item.creditEnhancementRanking[i].priorityName}资产支持证券的信用等级为${item.creditEnhancementRanking[i].preGrade};`;
        }
        allNeedDay.resultStr = result
        reportData.value = item
      } else {
        ElMessage.warning(res4.msg)
      }
    }
    informationDialog.value = true
  }
  async function saveCase() {
    const data = {
      fileName: selectItem.value.name,
      status: 1,
      securityCreditRatingId: selectSecurityCreditRatingId.value,
      assetSecuritizationName: selectName.value,
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await SecuritiesDeclarationProfilesCreate(data)
    if (res.success) {
      ElMessage.success('上传资料成功！')
      informationDialog.value = false
      handleChangeStatus()
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function handleChangeStatus() {
    declareList.value.forEach(item => item.status = '0')
    const data = qs.stringify({
      securityCreditRatingId: selectSecurityCreditRatingId.value
    })
    let res = await GetAllDeclarationProfiles(data)
    if (res.success) {
      res.data.forEach(item => {
        declareList.value.forEach(b => {
          if (item.fileName == b.name) {
            b.status = '1'
          }
        })
      })
      //修改一下状态
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function closeAllList() {
    allListVisible.value = false
    getList()
  }
  return {
    showReport,
    filterSelectId,
    dataList,
    informationDialog,
    filterProject,
    showInformation,
    selectItem,
    declareList,
    isShowSave,
    filterDataList,
    projectpProposalsData,
    allNeedDay,
    selectName,
    saveCase,
    columns,
    reportData,
    allListVisible,
    closeAllList,
    columns1
  }
}